package com.liuwei.msmall.seckill.interceptor;

import com.liuwei.msmall.common.constant.AuthServiceConstant;
import com.liuwei.msmall.common.dto.MemberRespDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Classname LoginInterceptor
 * @Date 2020/10/23 17:36
 * @Created by 刘
 */


@Component
public class LoginInterceptor implements HandlerInterceptor {

    //创建一个线程共享数据
    public static final ThreadLocal<MemberRespDTO> loginUserLocal=new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", uri);
        /**
         * 拦截秒杀请求，进行登录判断
         */
        if (match){
            HttpSession session = request.getSession();
            MemberRespDTO user = (MemberRespDTO) session.getAttribute(AuthServiceConstant.LONGIN_USER);
            if (user!=null){
                //将用户的数据放在线程共享数据中
                loginUserLocal.set(user);
                //登录之后就放行
                return true;
            }

            //没登陆就,回到登录页登录
            session.setAttribute("nologinMsg","请先登录");
            response.sendRedirect("http://auth.msmall.com/login.html");
            return false;
        }

        //其他地址直接放行
       return true;
    }
}
